﻿using System;
using System.Messaging;
using System.Windows.Forms;
using NsbExtensions;
using NsbExtensions.Endpoints.Msmq;
using ObjectBuilder.SpringFramework;

namespace SampleManagedEndpoint
{
    internal delegate void NotifyDelegate(string message);

    public partial class MainForm : Form
    {
        private ManagedEndpoint _endpoint;

        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            btnStartStop_Click(null, null);
        }

        private void CreateEndpoint()
        {
            MsmqHelper.EnsureQueue("ManagedClient");
            MsmqHelper.EnsureQueue("EndpointMonitorService");

            //Choose messaging options
            var options = new MsmqUnicastOptions
                              {
                                  UseXmlSerialization = true
                              };

            //Create the endpoint
            _endpoint =
                MsmqEndpointConfigurationManager.CreateManagedEndpointWith<Builder>(options);
        }

       

        private void StartEndpoint()
        {
            Notify("Starting Endpoint");

            _endpoint.Start();

            Notify("Endpoint Started");
            btnStartStop.Text = "Stop";
        }

        private void StopEndpoint()
        {
            Notify("Stopping Endpoint");

            _endpoint.Stop();

            Notify("Endpoint Stopped");
            btnStartStop.Text = "Start";
        }

        public void Notify(string message)
        {
            if (InvokeRequired)
            {
                NotifyDelegate marshal = Notify;
                BeginInvoke(marshal, message);
            }
            else
            {
                txtStatus.Text += message + Environment.NewLine;
                txtStatus.Refresh();
            }
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (_endpoint == null)
                {
                    CreateEndpoint();
                }

                if (_endpoint.IsRunning)
                {
                    StopEndpoint();
                }
                else
                {
                    StartEndpoint();
                }
            }
            catch (Exception ex)
            {
                Notify(ex.Message + Environment.NewLine + ex.StackTrace);
                while (ex.InnerException != null)
                {
                    Notify(ex.InnerException.Message + Environment.NewLine + ex.StackTrace);
                    ex = ex.InnerException;
                }
            }
        }
    }
}